package com.wnhz.work.yz.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.AllLookDetialsAdapter;
import com.wnhz.work.yz.adapter.LookDetialsAdapter;
import com.wnhz.work.yz.bean.AllocationBean;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.LookDetailsBean;
import com.wnhz.work.yz.bean.LookDetialNumsBean;
import com.wnhz.work.yz.constant.Constants;
import com.wnhz.work.yz.utils.BroadCastReceiverUtil;
import com.wnhz.work.yz.utils.LogUtil;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 厨房单间配置
 */
public class LookDetials789Activity extends BaseActivity implements View.OnClickListener, BroadCastReceiverUtil.OnReceiveBroadcast {
    private static final String TAG = "LookDetials789Activity";
    private static final int REPLACE = 1001;//替换
    private static final int ADDEDWASH = 1002;//新增
    private ListView my_listView;
    private LookDetialsAdapter adapter;
    private LookDetailsBean Lbean = new LookDetailsBean();
    private TextView tv_all_price;
    private TextView tv_reset;
    private double endPrice;
    double chanjiaPrice;
    private BroadcastReceiver broadcastReceiver;
    private double replaceprice = 0.00;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_detials789);
        initTilte();
        intData();
        initView();
        EventBus.getDefault().register(this);
        broadcastReceiver = BroadCastReceiverUtil.registerBroadcastReceiver(LookDetials789Activity.this, new String[]{Constants.UPDATE_PRICE_ADD_KIT,Constants.UPDATE_PRICE_DEL_KIT,Constants.UPDATE_PRICE_INPUT_KIT}, this);
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        BroadCastReceiverUtil.unRegisterBroadcastReceiver(LookDetials789Activity.this, broadcastReceiver);
    }

    // 在Android的主线程中运行
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatePrice(LookDetialNumsBean b) {
        tv_all_price.setText(getPrice());
    }

    private String packId, skuId, goods_id;

    private void intData() {
        packId = getIntent().getStringExtra("package_id");
        skuId = getIntent().getStringExtra("sku_id");
        goods_id = getIntent().getStringExtra("goods_id");
        upLoad(skuId, packId);
        showDialog();
    }

    private void upLoad(String skuId, String packId) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("package_id", packId);
        map.put("sku_id", skuId);

        XUtil.Post(Url.KITCHEN_PACKAGEGOODSLIST, map, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Log.e("----", result + "");
                        super.onSuccess(result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String res = jsonObject.optString("result");
                            String info = jsonObject.optString("info");
                            if ("1".equals(res)) {
                                Gson gson = new Gson();
                                LookDetailsBean detailsBean = new LookDetailsBean();
                                detailsBean = gson.fromJson(result, LookDetailsBean.class);
                                Lbean = gson.fromJson(result, LookDetailsBean.class);
                                if (MyApplication.getInstance().getKitchenflag() == 1){
                                    MyApplication.getInstance().setKitchenBean(detailsBean);
                                    MyApplication.getInstance().setKitchenflag(2);
                                }

                                MyApplication.getInstance().setKitchenPackagePrice(Lbean.getInfo().getPrice());
                            } else {
                                findViewById(R.id.btn_main_right).setVisibility(View.GONE);
                                if ("-1".equals(res)) {
                                    info = "请重新登录";
                                }
                                MyToast(info);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        setData();
                        closeDialog();
                    }


                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        closeDialog();
                        super.onError(ex, isOnCallback);
                    }
                }

        );
    }


    private void initView() {
        findViewById(R.id.tv_reset).setOnClickListener(this);
        my_listView = (ListView) findViewById(R.id.my_listView);
        tv_all_price = (TextView) findViewById(R.id.tv_all_price);
        tv_reset = (TextView) findViewById(R.id.tv_reset);

        tv_reset.setOnClickListener(this);
    }

    private double getdoublePrice(double price) {
        BigDecimal d = new BigDecimal(price);
        return d.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    private String getPrice() {
        double total = 0;
        for (int i = 0; i < Lbean.getInfo().getCate_info().size(); i++) {
            for (int j = 0; j < Lbean.getInfo().getCate_info().get(i).getData().size(); j++) {
                double nums = 1;
                try {
                    nums = Double.parseDouble(Lbean.getInfo().getCate_info().get(i).getData().get(j).getGoods_nums());
                } catch (Exception e) {
                    nums = 1;
                }
                double price = 0;
                try {
                    price = Double.parseDouble(Lbean.getInfo().getCate_info().get(i).getData().get(j).getGoods_price());
                } catch (Exception e) {
                    price = 0;
                }
                total += nums * price;

            }
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(total);
    }

    private void setData() {
        if (Lbean.getInfo().getCan_buy().equals("1")) {
            tv_all_price.setText(Lbean.getInfo().getPrice() + "");
            chanjiaPrice = Double.parseDouble(Lbean.getInfo().getPrice()) - Double.parseDouble(getPrice());
        } else {
            tv_all_price.setText(Lbean.getInfo().getOprice() + "");
            chanjiaPrice = Double.parseDouble(Lbean.getInfo().getOprice()) - Double.parseDouble(getPrice());
        }



        adapter = new LookDetialsAdapter(this, Lbean.getInfo().getCate_info(), this, my_listView);
        adapter.setMyMenuItemClickListener(new LookDetialsAdapter.MyMenuItemClickListener() {
            @Override
            public void onMenuClick(SwipeMenuListView sm_list, AllLookDetialsAdapter mAdapter, int max_position, int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        Intent intent = new Intent(LookDetials789Activity.this, ReplaceActivity.class);
                        intent.putExtra("goodsId", Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_id());
                        intent.putExtra("max_position", max_position);
                        intent.putExtra("position", position);
                        intent.putExtra("packageId", goods_id);
                        intent.putExtra("is_old", Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getIs_old());
                        intent.putExtra("nums", Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_nums());
                        Log.e("____kitnums____",Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_nums());
                        MyApplication.getInstance().setKitnums(Double.parseDouble(Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_nums()));
                        startActivityForResult(intent, REPLACE);
                        mAdapter.notifyDataSetChanged();
                        sm_list.smoothOpenMenu(position);
                        adapter.notifyDataSetChanged();
//                        replaceprice = Double.parseDouble(Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_price());
                        MyApplication.getInstance().setKitchenPackagePrice(tv_all_price.getText().toString());
                        break;
                    case 1:
                        double allPrice = Double.parseDouble(tv_all_price.getText().toString());
                        double price1 = Double.parseDouble(Lbean.getInfo().getPrice());
                        double oPrice = Double.parseDouble(Lbean.getInfo().getOprice());
                        double bilv = price1/oPrice;
                        double deletePrice = Double.parseDouble(Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_price()) * Double.parseDouble(Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_nums());
//                        double deletePrice = Double.parseDouble(Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_price()) *MyApplication.getInstance().getKitnums();
                        String isadd = Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getIs_old();
                        Log.e("m" + max_position, "p" + position);
                        Log.e("----", Lbean.getInfo().getCate_info().get(max_position).getData().size() +"bb");
                        Log.e("----", "bb--------------"+MyApplication.getInstance().getKitnums());
                        Log.e("----" ,replaceprice +"aa--------------");
                        Log.e("--要删除的价格aaaa--" , ""+deletePrice);
                        replaceprice = Double.parseDouble(MyApplication.getInstance().getReplacepeice());
                        DecimalFormat df = new DecimalFormat("######0.00");
                        double getPrice = 0.00;
                        if ("1".equals(isadd)) {
                            double li = 1;
                            double bili = getdoublePrice(li);

                            if (replaceprice == 0.00){
                                double now = deletePrice;
                                getPrice = allPrice - now;
                                Log.e("老商品价格111",""+getPrice);
                            }else{
                                getPrice = allPrice -  deletePrice;
                                Log.e("老商品价格222",""+getPrice);
                            }
                            double f1 = getdoublePrice(getPrice);
                            Log.e("老商品价格",""+f1);
                            if (f1 > 0) {
                                tv_all_price.setText(df.format(f1) + "");
                            } else {
                                tv_all_price.setText("0.00");
                            }
                            Log.i(TAG, "onMenuClick:== " + bili);
                            MyApplication.getInstance().setKitchenPackagePrice(tv_all_price.getText().toString());
                        } else {
//                            double price = allPrice - deletePrice  * MyApplication.getInstance().getKitnums();
                            double price = allPrice - deletePrice ;
                            double f2 = getdoublePrice(price);
                            Log.e("老商品价格",""+f2);
                            if (f2 > 0) {
                                tv_all_price.setText(df.format(f2) + "");
                            } else {
                                tv_all_price.setText("0.00");
                            }
                            MyApplication.getInstance().setKitchenPackagePrice(tv_all_price.getText().toString());
                        }
                        Lbean.getInfo().getCate_info().get(max_position).getData().remove(position);
                        mAdapter.notifyDataSetChanged();
                        MyApplication.getInstance().setKitchenBean(Lbean);
                        adapter.notifyDataSetChanged();

                        break;

                    default:
                        break;
                }
            }
        });
        my_listView.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REPLACE://替换
                if (resultCode == RESULT_OK) {
                    int max_position = data.getIntExtra("max_position", 0);
                    int position = data.getIntExtra("position", 0);
                    AllocationBean bean = (AllocationBean) data.getSerializableExtra("data");
                    Double oldpricenum = Double.parseDouble(Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_price());
                    Lbean.getInfo().getCate_info().get(max_position).getData().remove(position);
                    LookDetailsBean.InfoEntity.CateInfoEntity.DataEntity dataEntity = a2d(bean);
                    Lbean.getInfo().getCate_info().get(max_position).getData().add(position, dataEntity);
                    double allPrice = Double.parseDouble(tv_all_price.getText().toString());
                    Log.e("新总价价格=allPrice=", "" + allPrice);

                    double price1 = Double.parseDouble(Lbean.getInfo().getPrice());
                    double oPrice = Double.parseDouble(Lbean.getInfo().getOprice());
                    double xishu = price1/oPrice;
                    double changePrice = Double.parseDouble(Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getGoods_price());
                    Log.e("改变价格 = changePrice = ", "" + changePrice);
                    String isadd = Lbean.getInfo().getCate_info().get(max_position).getData().get(position).getIs_old();

//                    String oldprice = MyApplication.getInstance().getKitchenBean().getInfo().getCate_info().get(max_position).getData().get(position).getGoods_price();
//                    Log.e("原价格 = oldprice = ", "" + oldprice);
//                    Double oldpricenum = Double.parseDouble(oldprice);
                    Double packageprice = Double.parseDouble(MyApplication.getInstance().getKitchenPackagePrice());
                    Log.e("原价",""+oldpricenum);
                    Log.e("系数",""+xishu);
                    Double a = MyApplication.getInstance().getKitnums();
                    if(oldpricenum - changePrice > 0){//现在商品的价格大于替换价格
                        Double chajia = oldpricenum - changePrice;
                        Log.e("差价1",""+chajia);
                        endPrice = packageprice - (chajia *a);
                        MyApplication.getInstance().setKitchenPackagePrice(""+endPrice);
                    }else if (oldpricenum - changePrice <= 0){
                        Log.e("差价2",""+(changePrice-oldpricenum)*a);

                        endPrice = packageprice + ((changePrice-oldpricenum)*a);
                        MyApplication.getInstance().setKitchenPackagePrice(""+endPrice);
                    }

                    Log.e("---替换的最后的价格--", endPrice + "");
                    DecimalFormat df = new DecimalFormat("######0.00");
                    tv_all_price.setText(df.format(endPrice) + "");
//                    tv_all_price.setText(getPrice());
                    adapter.notifyDataSetChanged();
                }
                break;

            case ADDEDWASH://新增
                if (resultCode == RESULT_OK) {
                    int position = data.getIntExtra("position", 0);
                    AllocationBean bean = (AllocationBean) data.getSerializableExtra("data");
                    LookDetailsBean.InfoEntity.CateInfoEntity.DataEntity dataEntity = a2d(bean);
                    Lbean.getInfo().getCate_info().get(position).getData().add(dataEntity);
                    double allPrice = Double.parseDouble(tv_all_price.getText().toString());
                    double addPrice = Double.parseDouble(bean.getGoods_price() + "");
                    double price = addPrice + allPrice;
                    double f2 = getdoublePrice(price);
                    tv_all_price.setText(f2 + "");
//                    tv_all_price.setText(getPrice());
                    adapter.notifyDataSetChanged();
                    MyApplication.getInstance().setKitchenBean(Lbean);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initTilte() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("单间配置");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.btn_main_right).setOnClickListener(this);
        TextView right = (TextView) findViewById(R.id.tv_right);
        right.setText("下一步");
    }


    private LookDetailsBean.InfoEntity.CateInfoEntity.DataEntity a2d(AllocationBean bean) {

        LookDetailsBean.InfoEntity.CateInfoEntity.DataEntity dataEntity = new LookDetailsBean.InfoEntity.CateInfoEntity.DataEntity();
        dataEntity.setIs_old(bean.getIs_old());
        dataEntity.setGoods_id(bean.getGoods_id());
        dataEntity.setGoods_name(bean.getGoods_name());
        dataEntity.setGoods_brand(bean.getGoods_brand());
        dataEntity.setGoods_pic(bean.getGoods_pic());
        dataEntity.setGoods_price(bean.getGoods_price());
        dataEntity.setGoods_nums(bean.getGoods_nums());
        dataEntity.setGoods_unit(bean.getGoods_unit());
        dataEntity.setSku_id(bean.getSku_id());
        dataEntity.setSku_info(bean.getSku_info());
        dataEntity.setSelect(false);
        return dataEntity;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                showDialogv7("未添加至购物车，确认返回后将被清空！", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                break;
            //下一步
            case R.id.btn_main_right:
                Intent intent = new Intent(this, AddChuFangActivity.class);
                intent.putExtra("bean", Lbean);
                intent.putExtra("sku_id", skuId);
                intent.putExtra("total_price", getPrice());
                startActivity(intent);
                break;
            //新增主体
            case R.id.tv_add:
                int position = (int) v.getTag();
                intent = new Intent(this, AddedWashActivity.class);
                intent.putExtra("position", position);
                intent.putExtra("packageId", goods_id);
                intent.putExtra("cateId", Lbean.getInfo().getCate_info().get(position).getCate_id());
                startActivityForResult(intent, ADDEDWASH);
                break;
            case R.id.tv_reset:
                showDialogv7("是否重置？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        upLoad(skuId, packId);
                    }
                });
                break;
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Constants.UPDATE_PRICE_ADD_KIT)) {
            adapter.notifyDataSetChanged();
            String goodsprice = MyApplication.getInstance().getKitchenPackagePrice_GoodsPrice();
            Double goodsprice_d = Double.parseDouble(goodsprice);
//            ha1 = Double.parseDouble(getPrice());
            DecimalFormat df = new DecimalFormat("######0.00");
//            double all_endPrice = Double.parseDouble(tv_all_price.getText().toString()) + (ha1 - ha);
            double all_endPrice = Double.parseDouble(tv_all_price.getText().toString()) + goodsprice_d;
            LogUtil.e("=增加价格==", all_endPrice + "");

            tv_all_price.setText("" + df.format(all_endPrice));
            MyApplication.getInstance().setKitchenPackagePrice(tv_all_price.getText().toString());
        }else if (intent.getAction().equals(Constants.UPDATE_PRICE_DEL_KIT)){
            adapter.notifyDataSetChanged();
            Double packageprice = Double.parseDouble(MyApplication.getInstance().getKitchenPackagePrice());
            String goodsprice = MyApplication.getInstance().getKitchenPackagePrice_GoodsPrice();
            Double goodsprice_d = Double.parseDouble(goodsprice);
            DecimalFormat df = new DecimalFormat("######0.00");
            double all_endPrice1 = Double.parseDouble(tv_all_price.getText().toString()) - goodsprice_d;

            LogUtil.e("=减少价格==", endPrice + "");
            if (packageprice < all_endPrice1){
                tv_all_price.setText("" + df.format(all_endPrice1));
            }else{
                tv_all_price.setText("" + df.format(all_endPrice1));
            }
            MyApplication.getInstance().setKitchenPackagePrice(tv_all_price.getText().toString());
        }else if (intent.getAction().equals(Constants.UPDATE_PRICE_INPUT_KIT)){
            adapter.notifyDataSetChanged();
            Double packageprice = Double.parseDouble(MyApplication.getInstance().getKitchenPackagePrice());
            String goodsprice = MyApplication.getInstance().getKitchenPackagePrice_GoodsPrice();
            Double goodsprice_d = Double.parseDouble(goodsprice);
            DecimalFormat df = new DecimalFormat("######0.00");

            Log.e("商品单价",goodsprice);
            DecimalFormat df3 = new DecimalFormat("######0.00");
            Double oldnums = MyApplication.getInstance().getKitnums();
            Log.e("商品旧数量",""+oldnums);
            Double nownums = MyApplication.getInstance().getInputnums_kit();
            Log.e("商品新数量",""+nownums);
            Double cha_nums = nownums - oldnums;
            Log.e("商品数量差",""+cha_nums);
            Double chajia3 = goodsprice_d*cha_nums;
            Log.e("商品差价",""+chajia3);
            double all_endprice3 = Double.parseDouble(tv_all_price.getText().toString())+chajia3;
            tv_all_price.setText("" + df3.format(all_endprice3));
            //重新设置旧的数量
            MyApplication.getInstance().setKitnums(nownums);
            MyApplication.getInstance().setKitchenPackagePrice(tv_all_price.getText().toString());
        }
    }
}
